<?php
class Controller_Tests extends Controller_Base
{
	public function index()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Tests';
		$this->view->title = 'Tests Menu';
	}
	
	
	private function form()
	{
		if($this->request->isPost()){
			$isXhr = $this->request->isXhr();
			$name = (string)$this->request->getParam('name');
			$subject = (string)$this->request->getParam('subject');
			$model = new Model_Tests();
			$isValid = $model->isValid($name, $subject);
			if($isXhr){
				$this->disabledView = true;
				header('Content-type: text/json');
			}
			if(!$isValid){
				if($isXhr){
					echo json_encode(array('errorMessage' => 'All fields is mandatory'));
				}else{
					$this->view->errorMessage = 'All fields is mandatory';
				}
				return;
			}else{
				$testAdded = (bool)$model->save($this->request->getPost());
				if($isXhr){
					echo json_encode(array('testAdded' => $testAdded));
				}else{
					$this->redirect(array('ctrl' => 'tests', 'act' => 'lists'));
				}
			}
		}
	}
	
	
	public function add()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Add Test';
		$this->view->title = $this->view->pageTitle;
		$this->view->errorMessage = '';
		$this->view->test = new stdClass();
		$this->view->test->name =  (string)$this->request->getParam('name');
		$this->view->test->subject = (string)$this->request->getParam('subject');
		$this->test->id = (int)$this->request->getParam('id');
		$this->form();
	}
	
	public function update()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Update Test';
		$this->view->title = $this->view->pageTitle;
		$this->view->errorMessage = '';
		$id = (int)$this->request->getParam('id');
		if($id > 0){
			$model = new Model_DbTable_Tests();
			$this->view->test = $model->fetchOne(array(), array('id' => $id));
		}
		$this->form();
	}
	
	public function delete()
	{
		$this->disabledView = true;
		$id = (int)$this->request->getParam('id');
		$model = new Model_DbTable_Tests();
		$isDeleted = (bool)$model->delete(array('id' => $id));
		header('Content-type: text/json');
		echo json_encode(array('isDeleted' => $isDeleted));
	}
	
	public function table()
	{
		$model = new Model_DbTable_Tests();
		$this->view->tests = $model->fetchAll();
	}
	
	public function lists()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Tests Lists';
		$this->view->title = $this->view->pageTitle;
		
		$this->view->confirmTitle = 'Delete Test';
		$this->view->confirmMessage = 'This will delete all test data include questions and answers are you sure?';
		$model = new Model_DbTable_Tests();
		$this->view->tests = $model->fetchAll();
	}
}